package gr.gsis.cobol;

import gr.gsis.cobol.spec.FieldSpec;
import gr.gsis.cobol.spec.RecordSpec;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

public class FileSpecParser {

	public Set<RecordSpec> parse(InputStream istream) throws IOException {
		Set<RecordSpec> recordSpecs = new HashSet<RecordSpec>();
		
		Properties p = new Properties();
		p.load(istream);

		// Format is <recordType>.<position> for keys
		Set<String> recordTypes = new HashSet<String>();
		for (Object each: p.keySet()) {
			String key = (String) each;
			
			if (key.indexOf('.') == -1) {
				continue;
			}
			
			String[] parts = key.split("\\.");
			if (parts.length == 2) {
				recordTypes.add(parts[0]);
			}
		}

		for (String each: recordTypes) {
			List<FieldSpec> fieldSpecs = new ArrayList<FieldSpec>();
			
			int pos = 0;
			while (true) {
				String key = each + "." + pos;
				if (!p.containsKey(key)) {
					break;
				}

				String value = p.getProperty(key);
				String[] parts = value.split(",");
				String picture = PictureUtils.expand(parts[0]);
				String propertyName = null;
				String formatterId = null;
				if (parts.length > 1) {
					propertyName = parts[1].trim();
				}
				if (parts.length > 2) {
					formatterId = parts[2].trim();
				}
				
				fieldSpecs.add(new FieldSpec(picture, propertyName, formatterId));
				pos++;
			}
			
			String className = null;
			if (p.containsKey(each)) {
				className = p.getProperty(each);
			}
			
			recordSpecs.add(new RecordSpec(each.charAt(0), fieldSpecs, className));
		}
		
		return recordSpecs;
	}
	
}
